package com.tianji.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.remark.RemarkClient;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.course.CourseSimpleInfoDTO;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.chat.domain.dto.TaskDTO;
import com.tianji.chat.domain.po.Chat;
import com.tianji.chat.domain.po.Task;
import com.tianji.chat.domain.vo.TaskVO;
import com.tianji.chat.mapper.ChatMapper;
import com.tianji.chat.mapper.TaskMapper;
import com.tianji.chat.service.ITaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.domain.query.PageQuery;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static com.tianji.common.constants.Constant.DATA_FIELD_NAME_CREATE_TIME;
import static com.tianji.common.constants.Constant.DATA_FIELD_NAME_LIKED_TIME;

/**
 * <p>
 * 对话任务表 服务实现类
 * </p>
 *
 * @author pku-hlp
 * @since 2024-01-13
 */
@Service
@RequiredArgsConstructor
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {

    //调用其他服务的api
    private final UserClient userClient;
    private final ChatMapper chatMapper;
    private final RemarkClient remarkClient;

    @Override
    public void saveTask(TaskDTO taskDTO) {
        // 1.获取当前登录的用户id
        Long userId = UserContext.getUser();
        // 2.数据封装
        Task question = BeanUtils.copyBean(taskDTO, Task.class);
        question.setUserId(userId);
        // 3.写入数据库
        save(question);
    }

    @Override
    public void updateTask(Long id, TaskDTO taskDTO) {
        // 1.获取当前登录用户
        Long userId = UserContext.getUser();
        // 2.查询当前任务
        Task q = getById(id);
        if (q == null) {
            throw new BadRequestException("任务不存在");
        }
        // 3.判断是否是当前用户的
        if (!q.getUserId().equals(userId)) {
            // 不是，抛出异常
            throw new BadRequestException("无权修改他人的问题");
        }
        // 4.修改任务
        Task question = BeanUtils.toBean(taskDTO, Task.class);
        question.setId(id);
        updateById(question);

    }

    @Override
    public TaskVO queryTaskById(Long id) {

        // 1.根据id查询数据
        Task question = getById(id);
        // 2.数据校验
        if(question == null || question.getHidden()){
            // 没有数据或者是被隐藏了
            return null;
        }
        // 3.查询提问者信息
        UserDTO user = null;
        if(!question.getAnonymity()){
            user = userClient.queryUserById(question.getUserId());
        }
        // 4.封装VO
        TaskVO vo = BeanUtils.copyBean(question, TaskVO.class);
        if (user != null) {
            vo.setUserName(user.getName());
            vo.setUserIcon(user.getIcon());
        }
        return vo;
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        // 1.获取当前登录用户
        Long userId = UserContext.getUser();
        // 2.查询当前问题
        Task q = getById(id);
        if (q == null) {
            return;
        }
        // 3.判断是否是当前用户的任务
        if (!q.getUserId().equals(userId)) {
            // 不是，抛出异常
            throw new BadRequestException("无权删除他人的任务");
        }
        // 4.删除任务
        removeById(id);
        // 5.删除任务下的所有对话
        chatMapper.delete(
                new QueryWrapper<Chat>().lambda().eq(Chat::getTaskId, id)
        );

    }

    @Override
    public PageDTO<TaskVO> queryQuestionPage(PageQuery query) {
        // 1.获取当前登录用户
        Long userId = UserContext.getUser();
        // 2.分页查询
        // select * from task where user_id = #{userId} order by update_time limit 0, 5
        Page<Task> page = lambdaQuery()
                .eq(Task::getUserId, userId) // where user_id = #{userId}
                .page(query.toMpPage("update_time", false));
        List<Task> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }

        // 3.封装VO返回
        List<TaskVO> list = new ArrayList<>(records.size());
        // 4.1.循环遍历，把Task转为VO
        for (Task r : records) {
            // 4.2.拷贝基础属性到vo
            TaskVO vo = BeanUtils.copyBean(r, TaskVO.class);
            list.add(vo);
        }
        return PageDTO.of(page, list);
    }

    @Override
    public PageDTO<TaskVO> queryMostLikePage(PageQuery query) {
        // 分页查询
        Page<Task> page = lambdaQuery()
                .eq(true, Task::getHidden, false)
                .page(query.toMpPage(
                        new OrderItem("liked_times", false),
                        new OrderItem("create_time", false))
                );
        List<Task> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }


        // 3.封装VO返回
        List<TaskVO> list = new ArrayList<>(records.size());
        // 4.1.循环遍历，把Task转为VO
        for (Task r : records) {
            // 4.2.拷贝基础属性到vo
            TaskVO vo = BeanUtils.copyBean(r, TaskVO.class);
            list.add(vo);
        }
        return PageDTO.of(page, list);


    }
}


/*
*  // 数据处理
        Set<Long> userIds = new HashSet<>();
        Set<Long> taskIds = new HashSet<>();
        for (Task r : records) {
            if(!r.getAnonymity() ) {
                // 非匿名
                userIds.add(r.getUserId());
            }
            taskIds.add(r.getId());
        }
        // 查询用户
        Map<Long, UserDTO> userMap = new HashMap<>(userIds.size());
        if(userIds.size() > 0) {
            List<UserDTO> users = userClient.queryUserByIds(userIds);
            userMap = users.stream().collect(Collectors.toMap(UserDTO::getId, u -> u));
        }
        // 查询用户点赞状态
        Set<Long> bizLiked = remarkClient.isBizLiked(taskIds);
        // 处理VO
        List<TaskVO> list = new ArrayList<>(records.size());
        for (Task r : records) {
            // 拷贝基础属性
            TaskVO taskvo = BeanUtils.toBean(r, TaskVO.class);
            list.add(taskvo);
            if(!r.getAnonymity() ){
                UserDTO userDTO = userMap.get(r.getUserId());
                if (userDTO != null) {
                    taskvo.setUserIcon(userDTO.getIcon());
                    taskvo.setUserName(userDTO.getName());
                }
            }

            // 设置点赞状态
            taskvo.setLiked(bizLiked.contains(r.getId()));
        }
        return new PageDTO<>(page.getTotal(), page.getPages(), list);
        *
        * */